from django.shortcuts import render

# Create your views here.
from rest_framework import serializers
from rest_framework import exceptions
from rest_framework.views import APIView
from rest_framework.response import Response
import re
from django.core.validators import EmailValidator
from django.forms.models import model_to_dict
from app01 import models

class RegexVakidator():
    def __init__(self,base):
        self.base = str(base)

    def __call__(self,value):
        match_object = re.match(self.base,value)
        if not match_object:
            raise serializers.ValidationError("格式错误")


"""数据校验示例1"""
class UserSerializer(serializers.Serializer):
    username = serializers.CharField(label="姓名",min_length=6,max_length=32)
    age = serializers.IntegerField(label="年龄",min_value=0,max_value=200)
    level = serializers.ChoiceField(label="级别",choices=models.UserInfo.level_choices)
    email = serializers.CharField(label="邮箱",validators=[EmailValidator,])
    email1 = serializers.EmailField(label="邮箱1")
    email2 = serializers.CharField(label="邮箱2",validators=[RegexVakidator(r"^\w+@\w+\.\w+$"),])
    email3 = serializers.CharField(label="邮箱3")

    def validate_email3(self, value):
        """钩子函数，用于验证某个字段"""
        if re.match(r"^\w+@\w+\.\w+$",value):
            return value
        raise exceptions.ValidationError("邮箱格式错误")

class UserView(APIView):
    """用户管理"""
    def post(self,request):
        """添加用户"""
        ser = UserSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"code":1006,"data":ser.errors})
        print(ser.validated_data)
        return Response({"code":0,"data":"创建成功"})


"""数据校验示例2"""
class UserModelSerializer(serializers.ModelSerializer):

    email2 = serializers.CharField(label="邮箱",validators=[RegexVakidator(r"^\w+@\w+\.\w+$")])
    email3 = serializers.CharField(label="邮箱3")

    class Meta:
        model = models.UserInfo
        fields = ["username","age","level","email","email2","email3"]
        extra_kwargs = {
            'username':{'min_length':6,"max_length":32},
            "email":{"validators":[EmailValidator,]}
        }

    def validate_email3(self, value):
        """钩子函数，用于验证某个字段"""
        if re.match(r"^\w+@\w+\.\w+$",value):
            return value
        raise exceptions.ValidationError("邮箱格式错误")


class UserView2(APIView):
    """用户管理"""

    def post(self,request):
        """添加用户"""
        ser = UserModelSerializer(data=request.data)
        print(ser)
        if not ser.is_valid():
            return Response({"code":1006,"data":ser.errors})
        ser.validated_data.pop("email2")
        ser.validated_data.pop("email3")
        ser.save(password = "123",depart_id ="2")
        return Response({"code": 0, "data": "创建成功"})



"""数据校验示例3 含外键、多表相连"""
class UserModelSerializer3(serializers.ModelSerializer):

    class Meta:
        model = models.UserInfo
        fields = ["username","age","level","depart","roles","email"]
        extra_kwargs = {
            'username':{'min_length':6,"max_length":32},
            "email":{"validators":[EmailValidator,]}
        }


class UserView3(APIView):
    """用户管理"""

    def post(self,request):
        """添加用户"""
        ser = UserModelSerializer3(data=request.data)
        print(ser)
        if not ser.is_valid():
            return Response({"code":1006,"data":ser.errors})
        ser.save(password = "123")
        return Response({"code": 0, "data": "创建成功"})


    """数据序列化 示例1"""
    def get(self,request):
        """查询用户"""
        queryset = models.UserInfo.objects.all()
        ser = UserModelSerializer3(instance=queryset,many=True)
        print(ser.data)
        return Response({"code":0,"data":ser.data})


"""数据序列化 示例2"""

class UserModelSerializer4(serializers.ModelSerializer):

    level_text = serializers.CharField(source="get_level_display")
    depart = serializers.CharField(source="depart.title")

    roles = serializers.SerializerMethodField()
    extra = serializers.SerializerMethodField()

    class Meta:
        model = models.UserInfo
        fields = ["username","age","level_text","depart","roles","email","extra"]

    def get_roles(self,obj):
        data_list = obj.roles.all()
        return [model_to_dict(item,["id","title"]) for item in data_list]

    def get_extra(self,obj):
        return 6666



class UserView4(APIView):
    """用户管理"""
    def get(self,request):
        """查询用户"""
        queryset = models.UserInfo.objects.all()
        ser = UserModelSerializer4(instance=queryset,many=True)
        print(ser.data)
        return Response({"code":0,"data":ser.data})




"""数据序列化 示例3"""
class DepartModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Department
        fields = "__all__"


class RoleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        fields = "__all__"


class UserModelSerializer5(serializers.ModelSerializer):
    level_text = serializers.CharField(source="get_level_display")
    depart = DepartModelSerializer()
    roles = RoleModelSerializer(many=True)

    class Meta:
        model = models.UserInfo
        fields = ["username","age","email","level_text","depart","roles"]


class UserView5(APIView):
    """用户管理"""
    def get(self,request):
        queryset = models.UserInfo.objects.all()
        ser = UserModelSerializer5(instance=queryset,many=True)
        print(ser.data)

        return Response({"code":200,"data":ser.data})






